<!-- 角色管理 -->
<template>
  <div>
    <el-form :inline="true">
      <el-form-item>
        <el-input
          clearable
          v-model="searchFrom.name"
          placeholder="请输入内容"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" plain @click="serachRoleList">搜索</el-button>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="dialogVisible = true">新增</el-button>
      </el-form-item>
      <el-form-item>
        <el-button
          type="danger"
          @click="deleteHandle(null)"
          :disabled="delStatus"
          >批量删除</el-button
        >
      </el-form-item>
    </el-form>

    <el-table
      ref="multipleTable"
      stripe
      border
      :data="tableData"
      tooltip-effect="dark"
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"> </el-table-column>
      <el-table-column prop="name" label="名称" width="160"> </el-table-column>
      <el-table-column prop="code" label="唯一编码" width="160">
      </el-table-column>
      <el-table-column
        prop="remark"
        label="描述"
        width="1000"
        show-overflow-tooltip
      >
      </el-table-column>
      <el-table-column prop="address" label="状态" width="130">
        <template slot-scope="scope">
          <el-tag type="success" size="small" v-if="scope.row.statu === 1"
            >正常</el-tag
          >
          <el-tag type="danger" size="small" v-if="scope.row.statu === 0"
            >禁用</el-tag
          >
        </template>
      </el-table-column>
      <el-table-column prop="address" label="操作">
        <template slot-scope="scope">
          <el-button @click="permHandle(scope.row.id)" type="text" size="small"
            >分配权限</el-button
          >
          <el-divider direction="vertical"></el-divider>
          <el-button @click="editHandle(scope.row.id)" type="text" size="small"
            >编辑</el-button
          >
          <el-divider direction="vertical"></el-divider>
          <!-- <el-button type="text" size="small">删除</el-button> -->
          <el-button type="text" @click="deleteHandle(scope.row.id)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页框 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage4"
      :page-sizes="[10, 20, 30, 40]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="totalCount"
    >
    </el-pagination>

    <!-- 新增对话框 -->
    <el-dialog
      title="新增角色"
      :visible.sync="dialogVisible"
      width="650px"
      :before-close="handleClose"
    >
      <!-- 弹窗表单 -->
      <el-form
        :model="userForm"
        :rules="userFormRules"
        ref="userForm"
        label-width="100px"
        class="demo-userForm"
      >
        <el-form-item label="角色名称" prop="name" label-width="100px">
          <el-input v-model="userForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="唯一编码" prop="code" label-width="100px">
          <el-input v-model="userForm.code" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="remark" label-width="100px">
          <el-input v-model="userForm.remark" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="statu" label-width="100px">
          <el-radio-group v-model="userForm.statu">
            <el-radio :label="0">禁用</el-radio>
            <el-radio :label="1">正常</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('userForm')"
            >提交</el-button
          >
          <el-button @click="resetForm('userForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 分配权限弹窗 -->
    <el-dialog
      title="分配权限"
      :visible.sync="permDialogVisible"
      width="650px"
      :before-close="handleClose"
    >
      <el-form :model="permForm">
        <!--  -->
        <el-tree
          :data="permTreeData"
          show-checkbox
          node-key="id"
          ref="permTree"
          :props="defaultProps"
          :default-expand-all="true"
          :check-strictly="true"
        >
        </el-tree>
      </el-form>
      <span slot="footer" class="dialog-footer" style="text-align:right;">
        <el-button @click="permDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitPermFormHandle('permForm')"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
//这里可以导入其他文件(比如:组件、工具js、)
//例如：import 组件名 from '组件路径'
export default {
  //import引入的组件需要注入到对象中才能使用
  data() {
    return {
      dialogVisible: false,
      permDialogVisible: false,
      currentPage4: 4,
      totalCount: 50,
      pageSize: 10,
      currPage: 1,
      searchFrom: {
        name: ""
      },
      userForm: {
        name: "",
        code: "",
        describe: "",
        remark: "",
        statu: ""
      },
      userFormRules: {
        name: [{ required: true, message: "请输入角色名称", trigger: "blur" }],
        perms: [{ required: true, message: "请输入唯一编码", trigger: "blur" }],
        statu: [{ required: true, message: "请选择状态", trigger: "blur" }]
      },
      tableData: [],
      delStatus: true,
      multipleSelection: [],
      permForm: {},
      permTreeData: [],
      defaultProps: {
        children: "children",
        label: "name"
      }
    };
  },

  components: {},

  computed: {},

  // mounted: {},

  methods: {
    resetChecked() {
      this.$refs.tree.setCheckedKeys([]);
    },
    getRoleList() {
      this.$http.get("/sys/role/list").then(res => {
        console.log("role:", res);
        this.tableData = res.data.data.list;
        this.totalCount = res.data.data.totalCount;
        this.pageSize = res.data.data.pageSize;
        this.currPage = res.data.data.currPage;
      });
    },
    serachRoleList() {
      this.$http
        .get("/sys/role/list", {
          params: {
            name: this.searchFrom.name,
            currPage: this.currPage,
            size: this.pageSize
          }
        })
        .then(res => {
          this.tableData = res.data.data.list;
          this.totalCount = res.data.data.totalCount;
          this.pageSize = res.data.data.pageSize;
          this.currPage = res.data.data.currPage;
        });
    },
    editHandle(id) {
      // alert(id);
      this.$http.get("/sys/role/info/" + id).then(res => {
        //数据封装
        this.userForm = res.data.data;
        //回显编辑菜单
        this.dialogVisible = true;
      });
    },
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then(_ => {
          done();
          this.userForm = {};
          this.$refs["userForm"].resetFields();
        })
        .catch(_ => {});
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          //具体的逻辑
          // alert("表单提交")
          this.$http
            .post(
              "/sys/role/" + (this.userForm.id != null ? "update" : "save"),
              this.userForm
            )
            .then(res => {
              this.$message({
                showcClose: true,
                type: "success",
                message: "提交成功!",
                onClose: () => {
                  //更新成功后 刷新菜单列表
                  this.getRoleList();
                }
              });
              this.userForm = {};
              this.$refs[formName].resetFields();
              this.dialogVisible = false;
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    submitPermFormHandle(formName) {
      let Ids = this.$refs.permTree.getCheckedNodes();
      let menuIds = [];
      Ids.forEach(item => {
        menuIds.push(item.id);
      });
      console.log("菜单Id", menuIds);

      this.$http
        .post("/sys/role/permIds/" + this.permForm.id, menuIds)
        .then(res => {
          this.$message({
            showcClose: true,
            type: "success",
            message: "提交成功!",
            onClose: () => {
              //更新成功后 刷新菜单列表
              this.getRoleList();
            }
          });
          this.permDialogVisible = false;
        });
    },
    deleteHandle(id) {
      let ids = [];
      if (id) {
        ids.push(id);
      } else {
        this.multipleSelection.forEach(item => {
          ids.push(item.id);
        });
      }

      this.$confirm("删除当前选中的角色, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.$http.post("/sys/role/delete/", ids).then(res => {
            this.$message({
              type: "success",
              message: "删除成功!",
              onClose: () => {
                //更新成功后 刷新菜单列表
                this.getRoleList();
              }
            });
          });
          alert("delete");
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    //多选框
    handleSelectionChange(val) {
      console.log("handleSelectionChange:", val);
      this.multipleSelection = val;

      //激活批量删除
      this.delStatus = val.length === 0;
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pageSize = val;
      this.serachRoleList();
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.currPage = val;
      this.serachRoleList();
    },
    permHandle(id) {
      // this.$http.get("/sys/role/perm/" + id).then(res => {
      //   alert("获取菜单列表");
      // });
      this.$http.get("/sys/role/info/" + id).then(res => {
        this.$refs.permTree.setCheckedKeys(res.data.data.menuIds);
        this.permForm = res.data.data;
      });
      this.permDialogVisible = true;
    }
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {
    this.getRoleList();

    this.$http.get("/sys/menu/list").then(res => {
      this.permTreeData = res.data.data;
    });
  }
};
</script>
<style scoped>
.el-pagination {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}
</style>
